home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / pkg_resources.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-13  |  58KB  |  2,064 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. import sys
  5. import os
  6. import zipimport
  7. import time
  8. import re
  9. import imp
  10. import new
  11. import pkgutil
  12.  
  13. try:
  14.     frozenset
  15. except NameError:
  16.     from sets import ImmutableSet as frozenset
  17.  
  18. from os import utime, rename, unlink
  19. from os import open as os_open
  20.  
  21. def get_supported_platform():
  22.     plat = get_build_platform()
  23.     m = macosVersionString.match(plat)
  24.     if m is not None and sys.platform == 'darwin':
  25.         
  26.         try:
  27.             plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
  28.         except ValueError:
  29.             pass
  30.         except:
  31.             None<EXCEPTION MATCH>ValueError
  32.         
  33.  
  34.     None<EXCEPTION MATCH>ValueError
  35.     return plat
  36.  
  37. __all__ = [
  38.     'require',
  39.     'run_script',
  40.     'get_provider',
  41.     'get_distribution',
  42.     'load_entry_point',
  43.     'get_entry_map',
  44.     'get_entry_info',
  45.     'iter_entry_points',
  46.     'resource_string',
  47.     'resource_stream',
  48.     'resource_filename',
  49.     'resource_listdir',
  50.     'resource_exists',
  51.     'resource_isdir',
  52.     'declare_namespace',
  53.     'working_set',
  54.     'add_activation_listener',
  55.     'find_distributions',
  56.     'set_extraction_path',
  57.     'cleanup_resources',
  58.     'get_default_cache',
  59.     'Environment',
  60.     'WorkingSet',
  61.     'ResourceManager',
  62.     'Distribution',
  63.     'Requirement',
  64.     'EntryPoint',
  65.     'ResolutionError',
  66.     'VersionConflict',
  67.     'DistributionNotFound',
  68.     'UnknownExtra',
  69.     'ExtractionError',
  70.     'parse_requirements',
  71.     'parse_version',
  72.     'safe_name',
  73.     'safe_version',
  74.     'get_platform',
  75.     'compatible_platforms',
  76.     'yield_lines',
  77.     'split_sections',
  78.     'safe_extra',
  79.     'to_filename',
  80.     'ensure_directory',
  81.     'normalize_path',
  82.     'EGG_DIST',
  83.     'BINARY_DIST',
  84.     'SOURCE_DIST',
  85.     'CHECKOUT_DIST',
  86.     'DEVELOP_DIST',
  87.     'IMetadataProvider',
  88.     'IResourceProvider',
  89.     'FileMetadata',
  90.     'PathMetadata',
  91.     'EggMetadata',
  92.     'EmptyProvider',
  93.     'empty_provider',
  94.     'NullProvider',
  95.     'EggProvider',
  96.     'DefaultProvider',
  97.     'ZipProvider',
  98.     'register_finder',
  99.     'register_namespace_handler',
  100.     'register_loader_type',
  101.     'fixup_namespace_packages',
  102.     'get_importer',
  103.     'run_main',
  104.     'AvailableDistributions']
  105.  
  106. class ResolutionError(Exception):
  107.     
  108.     def __repr__(self):
  109.         return self.__class__.__name__ + repr(self.args)
  110.  
  111.  
  112.  
  113. class VersionConflict(ResolutionError):
  114.     pass
  115.  
  116.  
  117. class DistributionNotFound(ResolutionError):
  118.     pass
  119.  
  120.  
  121. class UnknownExtra(ResolutionError):
  122.     pass
  123.  
  124. _provider_factories = { }
  125. PY_MAJOR = sys.version[:3]
  126. EGG_DIST = 3
  127. BINARY_DIST = 2
  128. SOURCE_DIST = 1
  129. CHECKOUT_DIST = 0
  130. DEVELOP_DIST = -1
  131.  
  132. def register_loader_type(loader_type, provider_factory):
  133.     _provider_factories[loader_type] = provider_factory
  134.  
  135.  
  136. def get_provider(moduleOrReq):
  137.     if isinstance(moduleOrReq, Requirement):
  138.         if not working_set.find(moduleOrReq):
  139.             pass
  140.         return require(str(moduleOrReq))[0]
  141.     
  142.     
  143.     try:
  144.         module = sys.modules[moduleOrReq]
  145.     except KeyError:
  146.         __import__(moduleOrReq)
  147.         module = sys.modules[moduleOrReq]
  148.  
  149.     loader = getattr(module, '__loader__', None)
  150.     return _find_adapter(_provider_factories, loader)(module)
  151.  
  152.  
  153. def _macosx_vers(_cache = []):
  154.     if not _cache:
  155.         info = os.popen('/usr/bin/sw_vers').read().splitlines()
  156.         for line in info:
  157.             (key, value) = line.split(None, 1)
  158.             if key == 'ProductVersion:':
  159.                 _cache.append(value.strip().split('.'))
  160.                 break
  161.                 continue
  162.         else:
  163.             raise ValueError, 'What?!'
  164.     
  165.     return _cache[0]
  166.  
  167.  
  168. def _macosx_arch(machine):
  169.     return {
  170.         'PowerPC': 'ppc',
  171.         'Power_Macintosh': 'ppc' }.get(machine, machine)
  172.  
  173.  
  174. def get_build_platform():
  175.     get_platform = get_platform
  176.     import distutils.util
  177.     plat = get_platform()
  178.     if sys.platform == 'darwin' and not plat.startswith('macosx-'):
  179.         
  180.         try:
  181.             version = _macosx_vers()
  182.             machine = os.uname()[4].replace(' ', '_')
  183.             return 'macosx-%d.%d-%s' % (int(version[0]), int(version[1]), _macosx_arch(machine))
  184.         except ValueError:
  185.             pass
  186.         except:
  187.             None<EXCEPTION MATCH>ValueError
  188.         
  189.  
  190.     None<EXCEPTION MATCH>ValueError
  191.     return plat
  192.  
  193. macosVersionString = re.compile('macosx-(\\d+)\\.(\\d+)-(.*)')
  194. darwinVersionString = re.compile('darwin-(\\d+)\\.(\\d+)\\.(\\d+)-(.*)')
  195. get_platform = get_build_platform
  196.  
  197. def compatible_platforms(provided, required):
  198.     if provided is None and required is None or provided == required:
  199.         return True
  200.     
  201.     reqMac = macosVersionString.match(required)
  202.     if reqMac:
  203.         provMac = macosVersionString.match(provided)
  204.         if not provMac:
  205.             provDarwin = darwinVersionString.match(provided)
  206.             if provDarwin:
  207.                 dversion = int(provDarwin.group(1))
  208.                 macosversion = '%s.%s' % (reqMac.group(1), reqMac.group(2))
  209.                 if (dversion == 7 or macosversion >= '10.3' or dversion == 8) and macosversion >= '10.4':
  210.                     return True
  211.                 
  212.             
  213.             return False
  214.         
  215.         if provMac.group(1) != reqMac.group(1) or provMac.group(3) != reqMac.group(3):
  216.             return False
  217.         
  218.         if int(provMac.group(2)) > int(reqMac.group(2)):
  219.             return False
  220.         
  221.         return True
  222.     
  223.     return False
  224.  
  225.  
  226. def run_script(dist_spec, script_name):
  227.     ns = sys._getframe(1).f_globals
  228.     name = ns['__name__']
  229.     ns.clear()
  230.     ns['__name__'] = name
  231.     require(dist_spec)[0].run_script(script_name, ns)
  232.  
  233. run_main = run_script
  234.  
  235. def get_distribution(dist):
  236.     if isinstance(dist, basestring):
  237.         dist = Requirement.parse(dist)
  238.     
  239.     if isinstance(dist, Requirement):
  240.         dist = get_provider(dist)
  241.     
  242.     if not isinstance(dist, Distribution):
  243.         raise TypeError('Expected string, Requirement, or Distribution', dist)
  244.     
  245.     return dist
  246.  
  247.  
  248. def load_entry_point(dist, group, name):
  249.     return get_distribution(dist).load_entry_point(group, name)
  250.  
  251.  
  252. def get_entry_map(dist, group = None):
  253.     return get_distribution(dist).get_entry_map(group)
  254.  
  255.  
  256. def get_entry_info(dist, group, name):
  257.     return get_distribution(dist).get_entry_info(group, name)
  258.  
  259.  
  260. try:
  261.     from pkgutil import get_importer
  262. except ImportError:
  263.     import _pkgutil as pkgutil
  264.     get_importer = pkgutil.get_importer
  265.  
  266. import pkgutil
  267.  
  268. class IMetadataProvider:
  269.     
  270.     def has_metadata(name):
  271.         pass
  272.  
  273.     
  274.     def get_metadata(name):
  275.         pass
  276.  
  277.     
  278.     def get_metadata_lines(name):
  279.         pass
  280.  
  281.     
  282.     def metadata_isdir(name):
  283.         pass
  284.  
  285.     
  286.     def metadata_listdir(name):
  287.         pass
  288.  
  289.     
  290.     def run_script(script_name, namespace):
  291.         pass
  292.  
  293.  
  294.  
  295. class IResourceProvider(IMetadataProvider):
  296.     
  297.     def get_resource_filename(manager, resource_name):
  298.         pass
  299.  
  300.     
  301.     def get_resource_stream(manager, resource_name):
  302.         pass
  303.  
  304.     
  305.     def get_resource_string(manager, resource_name):
  306.         pass
  307.  
  308.     
  309.     def has_resource(resource_name):
  310.         pass
  311.  
  312.     
  313.     def resource_isdir(resource_name):
  314.         pass
  315.  
  316.     
  317.     def resource_listdir(resource_name):
  318.         pass
  319.  
  320.  
  321.  
  322. class WorkingSet(object):
  323.     
  324.     def __init__(self, entries = None):
  325.         self.entries = []
  326.         self.entry_keys = { }
  327.         self.by_key = { }
  328.         self.callbacks = []
  329.         if entries is None:
  330.             entries = sys.path
  331.         
  332.         for entry in entries:
  333.             self.add_entry(entry)
  334.         
  335.  
  336.     
  337.     def add_entry(self, entry):
  338.         self.entry_keys.setdefault(entry, [])
  339.         self.entries.append(entry)
  340.         for dist in find_distributions(entry, True):
  341.             self.add(dist, entry, False)
  342.         
  343.  
  344.     
  345.     def __contains__(self, dist):
  346.         return self.by_key.get(dist.key) == dist
  347.  
  348.     
  349.     def find(self, req):
  350.         dist = self.by_key.get(req.key)
  351.         if dist is not None and dist not in req:
  352.             raise VersionConflict(dist, req)
  353.         else:
  354.             return dist
  355.  
  356.     
  357.     def iter_entry_points(self, group, name = None):
  358.         for dist in self:
  359.             entries = dist.get_entry_map(group)
  360.             if name is None:
  361.                 for ep in entries.values():
  362.                     yield ep
  363.                 
  364.             if name in entries:
  365.                 yield entries[name]
  366.                 continue
  367.         
  368.  
  369.     
  370.     def run_script(self, requires, script_name):
  371.         ns = sys._getframe(1).f_globals
  372.         name = ns['__name__']
  373.         ns.clear()
  374.         ns['__name__'] = name
  375.         self.require(requires)[0].run_script(script_name, ns)
  376.  
  377.     
  378.     def __iter__(self):
  379.         seen = { }
  380.         for item in self.entries:
  381.             for key in self.entry_keys[item]:
  382.                 if key not in seen:
  383.                     seen[key] = 1
  384.                     yield self.by_key[key]
  385.                     continue
  386.             
  387.         
  388.  
  389.     
  390.     def add(self, dist, entry = None, insert = True):
  391.         if insert:
  392.             dist.insert_on(self.entries, entry)
  393.         
  394.         if entry is None:
  395.             entry = dist.location
  396.         
  397.         keys = self.entry_keys.setdefault(entry, [])
  398.         keys2 = self.entry_keys.setdefault(dist.location, [])
  399.         if dist.key in self.by_key:
  400.             return None
  401.         
  402.         self.by_key[dist.key] = dist
  403.         if dist.key not in keys:
  404.             keys.append(dist.key)
  405.         
  406.         if dist.key not in keys2:
  407.             keys2.append(dist.key)
  408.         
  409.         self._added_new(dist)
  410.  
  411.     
  412.     def resolve(self, requirements, env = None, installer = None):
  413.         requirements = list(requirements)[::-1]
  414.         processed = { }
  415.         best = { }
  416.         to_activate = []
  417.         while requirements:
  418.             req = requirements.pop(0)
  419.             if req in processed:
  420.                 continue
  421.             
  422.             dist = best.get(req.key)
  423.             if dist is None:
  424.                 dist = self.by_key.get(req.key)
  425.                 if dist is None:
  426.                     if env is None:
  427.                         env = Environment(self.entries)
  428.                     
  429.                     dist = best[req.key] = env.best_match(req, self, installer)
  430.                     if dist is None:
  431.                         raise DistributionNotFound(req)
  432.                     
  433.                 
  434.                 to_activate.append(dist)
  435.             
  436.             if dist not in req:
  437.                 raise VersionConflict(dist, req)
  438.             
  439.             requirements.extend(dist.requires(req.extras)[::-1])
  440.             processed[req] = True
  441.         return to_activate
  442.  
  443.     
  444.     def find_plugins(self, plugin_env, full_env = None, installer = None, fallback = True):
  445.         plugin_projects = list(plugin_env)
  446.         plugin_projects.sort()
  447.         error_info = { }
  448.         distributions = { }
  449.         if full_env is None:
  450.             env = Environment(self.entries)
  451.             env += plugin_env
  452.         else:
  453.             env = full_env + plugin_env
  454.         shadow_set = self.__class__([])
  455.         map(shadow_set.add, self)
  456.         for project_name in plugin_projects:
  457.             for dist in plugin_env[project_name]:
  458.                 req = [
  459.                     dist.as_requirement()]
  460.                 
  461.                 try:
  462.                     resolvees = shadow_set.resolve(req, env, installer)
  463.                 except ResolutionError:
  464.                     v = None
  465.                     error_info[dist] = v
  466.                     if fallback:
  467.                         continue
  468.                     else:
  469.                         break
  470.                     fallback
  471.  
  472.                 map(shadow_set.add, resolvees)
  473.                 distributions.update(dict.fromkeys(resolvees))
  474.                 break
  475.             
  476.         
  477.         distributions = list(distributions)
  478.         distributions.sort()
  479.         return (distributions, error_info)
  480.  
  481.     
  482.     def require(self, *requirements):
  483.         needed = self.resolve(parse_requirements(requirements))
  484.         for dist in needed:
  485.             self.add(dist)
  486.         
  487.         return needed
  488.  
  489.     
  490.     def subscribe(self, callback):
  491.         if callback in self.callbacks:
  492.             return None
  493.         
  494.         self.callbacks.append(callback)
  495.         for dist in self:
  496.             callback(dist)
  497.         
  498.  
  499.     
  500.     def _added_new(self, dist):
  501.         for callback in self.callbacks:
  502.             callback(dist)
  503.         
  504.  
  505.  
  506.  
  507. class Environment(object):
  508.     
  509.     def __init__(self, search_path = None, platform = get_supported_platform(), python = PY_MAJOR):
  510.         self._distmap = { }
  511.         self._cache = { }
  512.         self.platform = platform
  513.         self.python = python
  514.         self.scan(search_path)
  515.  
  516.     
  517.     def can_add(self, dist):
  518.         if self.python is None and dist.py_version is None or dist.py_version == self.python:
  519.             pass
  520.         return compatible_platforms(dist.platform, self.platform)
  521.  
  522.     
  523.     def remove(self, dist):
  524.         self._distmap[dist.key].remove(dist)
  525.  
  526.     
  527.     def scan(self, search_path = None):
  528.         if search_path is None:
  529.             search_path = sys.path
  530.         
  531.         for item in search_path:
  532.             for dist in find_distributions(item):
  533.                 self.add(dist)
  534.             
  535.         
  536.  
  537.     
  538.     def __getitem__(self, project_name):
  539.         
  540.         try:
  541.             return self._cache[project_name]
  542.         except KeyError:
  543.             project_name = project_name.lower()
  544.             if project_name not in self._distmap:
  545.                 return []
  546.             
  547.         except:
  548.             project_name not in self._distmap
  549.  
  550.         if project_name not in self._cache:
  551.             dists = self._cache[project_name] = self._distmap[project_name]
  552.             _sort_dists(dists)
  553.         
  554.         return self._cache[project_name]
  555.  
  556.     
  557.     def add(self, dist):
  558.         if self.can_add(dist) and dist.has_version():
  559.             dists = self._distmap.setdefault(dist.key, [])
  560.             if dist not in dists:
  561.                 dists.append(dist)
  562.                 if dist.key in self._cache:
  563.                     _sort_dists(self._cache[dist.key])
  564.                 
  565.             
  566.         
  567.  
  568.     
  569.     def best_match(self, req, working_set, installer = None):
  570.         dist = working_set.find(req)
  571.         if dist is not None:
  572.             return dist
  573.         
  574.         for dist in self[req.key]:
  575.             if dist in req:
  576.                 return dist
  577.                 continue
  578.         
  579.         return self.obtain(req, installer)
  580.  
  581.     
  582.     def obtain(self, requirement, installer = None):
  583.         if installer is not None:
  584.             return installer(requirement)
  585.         
  586.  
  587.     
  588.     def __iter__(self):
  589.         for key in self._distmap.keys():
  590.             if self[key]:
  591.                 yield key
  592.                 continue
  593.         
  594.  
  595.     
  596.     def __iadd__(self, other):
  597.         if isinstance(other, Distribution):
  598.             self.add(other)
  599.         elif isinstance(other, Environment):
  600.             for project in other:
  601.                 for dist in other[project]:
  602.                     self.add(dist)
  603.                 
  604.             
  605.         else:
  606.             raise TypeError("Can't add %r to environment" % (other,))
  607.         return self
  608.  
  609.     
  610.     def __add__(self, other):
  611.         new = self.__class__([], platform = None, python = None)
  612.         for env in (self, other):
  613.             new += env
  614.         
  615.         return new
  616.  
  617.  
  618. AvailableDistributions = Environment
  619.  
  620. class ExtractionError(RuntimeError):
  621.     pass
  622.  
  623.  
  624. class ResourceManager:
  625.     extraction_path = None
  626.     
  627.     def __init__(self):
  628.         self.cached_files = { }
  629.  
  630.     
  631.     def resource_exists(self, package_or_requirement, resource_name):
  632.         return get_provider(package_or_requirement).has_resource(resource_name)
  633.  
  634.     
  635.     def resource_isdir(self, package_or_requirement, resource_name):
  636.         return get_provider(package_or_requirement).resource_isdir(resource_name)
  637.  
  638.     
  639.     def resource_filename(self, package_or_requirement, resource_name):
  640.         return get_provider(package_or_requirement).get_resource_filename(self, resource_name)
  641.  
  642.     
  643.     def resource_stream(self, package_or_requirement, resource_name):
  644.         return get_provider(package_or_requirement).get_resource_stream(self, resource_name)
  645.  
  646.     
  647.     def resource_string(self, package_or_requirement, resource_name):
  648.         return get_provider(package_or_requirement).get_resource_string(self, resource_name)
  649.  
  650.     
  651.     def resource_listdir(self, package_or_requirement, resource_name):
  652.         return get_provider(package_or_requirement).resource_listdir(resource_name)
  653.  
  654.     
  655.     def extraction_error(self):
  656.         old_exc = sys.exc_info()[1]
  657.         if not self.extraction_path:
  658.             pass
  659.         cache_path = get_default_cache()
  660.         err = ExtractionError("Can't extract file(s) to egg cache\n\nThe following error occurred while trying to extract file(s) to the Python egg\ncache:\n\n  %s\n\nThe Python egg cache directory is currently set to:\n\n  %s\n\nPerhaps your account does not have write access to this directory?  You can\nchange the cache directory by setting the PYTHON_EGG_CACHE environment\nvariable to point to an accessible directory.\n" % (old_exc, cache_path))
  661.         err.manager = self
  662.         err.cache_path = cache_path
  663.         err.original_error = old_exc
  664.         raise err
  665.  
  666.     
  667.     def get_cache_path(self, archive_name, names = ()):
  668.         if not self.extraction_path:
  669.             pass
  670.         extract_path = get_default_cache()
  671.         target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
  672.         
  673.         try:
  674.             ensure_directory(target_path)
  675.         except:
  676.             self.extraction_error()
  677.  
  678.         self.cached_files[target_path] = 1
  679.         return target_path
  680.  
  681.     
  682.     def postprocess(self, tempname, filename):
  683.         if os.name == 'posix':
  684.             mode = (os.stat(tempname).st_mode | 365) & 4095
  685.             os.chmod(tempname, mode)
  686.         
  687.  
  688.     
  689.     def set_extraction_path(self, path):
  690.         if self.cached_files:
  691.             raise ValueError("Can't change extraction path, files already extracted")
  692.         
  693.         self.extraction_path = path
  694.  
  695.     
  696.     def cleanup_resources(self, force = False):
  697.         pass
  698.  
  699.  
  700.  
  701. def get_default_cache():
  702.     
  703.     try:
  704.         return os.environ['PYTHON_EGG_CACHE']
  705.     except KeyError:
  706.         pass
  707.  
  708.     if os.name != 'nt':
  709.         return os.path.expanduser('~/.python-eggs')
  710.     
  711.     app_data = 'Application Data'
  712.     app_homes = [
  713.         (('APPDATA',), None),
  714.         (('USERPROFILE',), app_data),
  715.         (('HOMEDRIVE', 'HOMEPATH'), app_data),
  716.         (('HOMEPATH',), app_data),
  717.         (('HOME',), None),
  718.         (('WINDIR',), app_data)]
  719.     for keys, subdir in app_homes:
  720.         dirname = ''
  721.         for key in keys:
  722.             if key in os.environ:
  723.                 dirname = os.path.join(dirname, os.environ[key])
  724.                 continue
  725.             break
  726.         elif subdir:
  727.             dirname = os.path.join(dirname, subdir)
  728.         
  729.         return os.path.join(dirname, 'Python-Eggs')
  730.     else:
  731.         raise RuntimeError('Please set the PYTHON_EGG_CACHE enviroment variable')
  732.  
  733.  
  734. def safe_name(name):
  735.     return re.sub('[^A-Za-z0-9.]+', '-', name)
  736.  
  737.  
  738. def safe_version(version):
  739.     version = version.replace(' ', '.')
  740.     return re.sub('[^A-Za-z0-9.]+', '-', version)
  741.  
  742.  
  743. def safe_extra(extra):
  744.     return re.sub('[^A-Za-z0-9.]+', '_', extra).lower()
  745.  
  746.  
  747. def to_filename(name):
  748.     return name.replace('-', '_')
  749.  
  750.  
  751. class NullProvider:
  752.     egg_name = None
  753.     egg_info = None
  754.     loader = None
  755.     
  756.     def __init__(self, module):
  757.         self.loader = getattr(module, '__loader__', None)
  758.         self.module_path = os.path.dirname(getattr(module, '__file__', ''))
  759.  
  760.     
  761.     def get_resource_filename(self, manager, resource_name):
  762.         return self._fn(self.module_path, resource_name)
  763.  
  764.     
  765.     def get_resource_stream(self, manager, resource_name):
  766.         return StringIO(self.get_resource_string(manager, resource_name))
  767.  
  768.     
  769.     def get_resource_string(self, manager, resource_name):
  770.         return self._get(self._fn(self.module_path, resource_name))
  771.  
  772.     
  773.     def has_resource(self, resource_name):
  774.         return self._has(self._fn(self.module_path, resource_name))
  775.  
  776.     
  777.     def has_metadata(self, name):
  778.         if self.egg_info:
  779.             pass
  780.         return self._has(self._fn(self.egg_info, name))
  781.  
  782.     
  783.     def get_metadata(self, name):
  784.         if not self.egg_info:
  785.             return ''
  786.         
  787.         return self._get(self._fn(self.egg_info, name))
  788.  
  789.     
  790.     def get_metadata_lines(self, name):
  791.         return yield_lines(self.get_metadata(name))
  792.  
  793.     
  794.     def resource_isdir(self, resource_name):
  795.         return self._isdir(self._fn(self.module_path, resource_name))
  796.  
  797.     
  798.     def metadata_isdir(self, name):
  799.         if self.egg_info:
  800.             pass
  801.         return self._isdir(self._fn(self.egg_info, name))
  802.  
  803.     
  804.     def resource_listdir(self, resource_name):
  805.         return self._listdir(self._fn(self.module_path, resource_name))
  806.  
  807.     
  808.     def metadata_listdir(self, name):
  809.         if self.egg_info:
  810.             return self._listdir(self._fn(self.egg_info, name))
  811.         
  812.         return []
  813.  
  814.     
  815.     def run_script(self, script_name, namespace):
  816.         script = 'scripts/' + script_name
  817.         if not self.has_metadata(script):
  818.             raise ResolutionError('No script named %r' % script_name)
  819.         
  820.         script_text = self.get_metadata(script).replace('\r\n', '\n')
  821.         script_text = script_text.replace('\r', '\n')
  822.         script_filename = self._fn(self.egg_info, script)
  823.         namespace['__file__'] = script_filename
  824.         if os.path.exists(script_filename):
  825.             execfile(script_filename, namespace, namespace)
  826.         else:
  827.             cache = cache
  828.             import linecache
  829.             cache[script_filename] = (len(script_text), 0, script_text.split('\n'), script_filename)
  830.             script_code = compile(script_text, script_filename, 'exec')
  831.             exec script_code in namespace, namespace
  832.  
  833.     
  834.     def _has(self, path):
  835.         raise NotImplementedError("Can't perform this operation for unregistered loader type")
  836.  
  837.     
  838.     def _isdir(self, path):
  839.         raise NotImplementedError("Can't perform this operation for unregistered loader type")
  840.  
  841.     
  842.     def _listdir(self, path):
  843.         raise NotImplementedError("Can't perform this operation for unregistered loader type")
  844.  
  845.     
  846.     def _fn(self, base, resource_name):
  847.         if resource_name:
  848.             return os.path.join(base, *resource_name.split('/'))
  849.         
  850.         return base
  851.  
  852.     
  853.     def _get(self, path):
  854.         if hasattr(self.loader, 'get_data'):
  855.             return self.loader.get_data(path)
  856.         
  857.         raise NotImplementedError("Can't perform this operation for loaders without 'get_data()'")
  858.  
  859.  
  860. register_loader_type(object, NullProvider)
  861.  
  862. class EggProvider(NullProvider):
  863.     
  864.     def __init__(self, module):
  865.         NullProvider.__init__(self, module)
  866.         self._setup_prefix()
  867.  
  868.     
  869.     def _setup_prefix(self):
  870.         path = self.module_path
  871.         old = None
  872.         while path != old:
  873.             if path.lower().endswith('.egg'):
  874.                 self.egg_name = os.path.basename(path)
  875.                 self.egg_info = os.path.join(path, 'EGG-INFO')
  876.                 self.egg_root = path
  877.                 break
  878.             
  879.             old = path
  880.             (path, base) = os.path.split(path)
  881.  
  882.  
  883.  
  884. class DefaultProvider(EggProvider):
  885.     
  886.     def _has(self, path):
  887.         return os.path.exists(path)
  888.  
  889.     
  890.     def _isdir(self, path):
  891.         return os.path.isdir(path)
  892.  
  893.     
  894.     def _listdir(self, path):
  895.         return os.listdir(path)
  896.  
  897.     
  898.     def get_resource_stream(self, manager, resource_name):
  899.         return open(self._fn(self.module_path, resource_name), 'rb')
  900.  
  901.     
  902.     def _get(self, path):
  903.         stream = open(path, 'rb')
  904.         
  905.         try:
  906.             return stream.read()
  907.         finally:
  908.             stream.close()
  909.  
  910.  
  911.  
  912. register_loader_type(type(None), DefaultProvider)
  913.  
  914. class EmptyProvider(NullProvider):
  915.     _isdir = _has = (lambda self, path: False)
  916.     
  917.     _get = lambda self, path: ''
  918.     
  919.     _listdir = lambda self, path: []
  920.     module_path = None
  921.     
  922.     def __init__(self):
  923.         pass
  924.  
  925.  
  926. empty_provider = EmptyProvider()
  927.  
  928. class ZipProvider(EggProvider):
  929.     eagers = None
  930.     
  931.     def __init__(self, module):
  932.         EggProvider.__init__(self, module)
  933.         self.zipinfo = zipimport._zip_directory_cache[self.loader.archive]
  934.         self.zip_pre = self.loader.archive + os.sep
  935.  
  936.     
  937.     def _zipinfo_name(self, fspath):
  938.         if fspath.startswith(self.zip_pre):
  939.             return fspath[len(self.zip_pre):]
  940.         
  941.         raise AssertionError('%s is not a subpath of %s' % (fspath, self.zip_pre))
  942.  
  943.     
  944.     def _parts(self, zip_path):
  945.         fspath = self.zip_pre + zip_path
  946.         if fspath.startswith(self.egg_root + os.sep):
  947.             return fspath[len(self.egg_root) + 1:].split(os.sep)
  948.         
  949.         raise AssertionError('%s is not a subpath of %s' % (fspath, self.egg_root))
  950.  
  951.     
  952.     def get_resource_filename(self, manager, resource_name):
  953.         if not self.egg_name:
  954.             raise NotImplementedError('resource_filename() only supported for .egg, not .zip')
  955.         
  956.         zip_path = self._resource_to_zip(resource_name)
  957.         eagers = self._get_eager_resources()
  958.         if '/'.join(self._parts(zip_path)) in eagers:
  959.             for name in eagers:
  960.                 self._extract_resource(manager, self._eager_to_zip(name))
  961.             
  962.         
  963.         return self._extract_resource(manager, zip_path)
  964.  
  965.     
  966.     def _extract_resource(self, manager, zip_path):
  967.         if zip_path in self._index():
  968.             for name in self._index()[zip_path]:
  969.                 last = self._extract_resource(manager, os.path.join(zip_path, name))
  970.             
  971.             return os.path.dirname(last)
  972.         
  973.         zip_stat = self.zipinfo[zip_path]
  974.         t = zip_stat[5]
  975.         d = zip_stat[6]
  976.         size = zip_stat[3]
  977.         date_time = ((d >> 9) + 1980, d >> 5 & 15, d & 31, (t & 65535) >> 11, t >> 5 & 63, (t & 31) * 2, 0, 0, -1)
  978.         timestamp = time.mktime(date_time)
  979.         
  980.         try:
  981.             real_path = manager.get_cache_path(self.egg_name, self._parts(zip_path))
  982.             if os.path.isfile(real_path):
  983.                 stat = os.stat(real_path)
  984.                 if stat.st_size == size and stat.st_mtime == timestamp:
  985.                     return real_path
  986.                 
  987.             
  988.             (outf, tmpnam) = _mkstemp('.$extract', dir = os.path.dirname(real_path))
  989.             os.write(outf, self.loader.get_data(zip_path))
  990.             os.close(outf)
  991.             utime(tmpnam, (timestamp, timestamp))
  992.             manager.postprocess(tmpnam, real_path)
  993.             
  994.             try:
  995.                 rename(tmpnam, real_path)
  996.             except os.error:
  997.                 if os.path.isfile(real_path):
  998.                     stat = os.stat(real_path)
  999.                     if stat.st_size == size and stat.st_mtime == timestamp:
  1000.                         return real_path
  1001.                     elif os.name == 'nt':
  1002.                         unlink(real_path)
  1003.                         rename(tmpnam, real_path)
  1004.                         return real_path
  1005.                     
  1006.                 
  1007.                 raise 
  1008.  
  1009.         except os.error:
  1010.             manager.extraction_error()
  1011.  
  1012.         return real_path
  1013.  
  1014.     
  1015.     def _get_eager_resources(self):
  1016.         if self.eagers is None:
  1017.             eagers = []
  1018.             for name in ('native_libs.txt', 'eager_resources.txt'):
  1019.                 if self.has_metadata(name):
  1020.                     eagers.extend(self.get_metadata_lines(name))
  1021.                     continue
  1022.             
  1023.             self.eagers = eagers
  1024.         
  1025.         return self.eagers
  1026.  
  1027.     
  1028.     def _index(self):
  1029.         
  1030.         try:
  1031.             return self._dirindex
  1032.         except AttributeError:
  1033.             ind = { }
  1034.             for path in self.zipinfo:
  1035.                 parts = path.split(os.sep)
  1036.                 while parts:
  1037.                     parent = os.sep.join(parts[:-1])
  1038.                     if parent in ind:
  1039.                         ind[parent].append(parts[-1])
  1040.                         break
  1041.                         continue
  1042.                     ind[parent] = [
  1043.                         parts.pop()]
  1044.             
  1045.             self._dirindex = ind
  1046.             return ind
  1047.  
  1048.  
  1049.     
  1050.     def _has(self, fspath):
  1051.         zip_path = self._zipinfo_name(fspath)
  1052.         if not zip_path in self.zipinfo:
  1053.             pass
  1054.         return zip_path in self._index()
  1055.  
  1056.     
  1057.     def _isdir(self, fspath):
  1058.         return self._zipinfo_name(fspath) in self._index()
  1059.  
  1060.     
  1061.     def _listdir(self, fspath):
  1062.         return list(self._index().get(self._zipinfo_name(fspath), ()))
  1063.  
  1064.     
  1065.     def _eager_to_zip(self, resource_name):
  1066.         return self._zipinfo_name(self._fn(self.egg_root, resource_name))
  1067.  
  1068.     
  1069.     def _resource_to_zip(self, resource_name):
  1070.         return self._zipinfo_name(self._fn(self.module_path, resource_name))
  1071.  
  1072.  
  1073. register_loader_type(zipimport.zipimporter, ZipProvider)
  1074.  
  1075. class FileMetadata(EmptyProvider):
  1076.     
  1077.     def __init__(self, path):
  1078.         self.path = path
  1079.  
  1080.     
  1081.     def has_metadata(self, name):
  1082.         return name == 'PKG-INFO'
  1083.  
  1084.     
  1085.     def get_metadata(self, name):
  1086.         if name == 'PKG-INFO':
  1087.             return open(self.path, 'rU').read()
  1088.         
  1089.         raise KeyError('No metadata except PKG-INFO is available')
  1090.  
  1091.     
  1092.     def get_metadata_lines(self, name):
  1093.         return yield_lines(self.get_metadata(name))
  1094.  
  1095.  
  1096.  
  1097. class PathMetadata(DefaultProvider):
  1098.     
  1099.     def __init__(self, path, egg_info):
  1100.         self.module_path = path
  1101.         self.egg_info = egg_info
  1102.  
  1103.  
  1104.  
  1105. class EggMetadata(ZipProvider):
  1106.     
  1107.     def __init__(self, importer):
  1108.         self.zipinfo = zipimport._zip_directory_cache[importer.archive]
  1109.         self.zip_pre = importer.archive + os.sep
  1110.         self.loader = importer
  1111.         if importer.prefix:
  1112.             self.module_path = os.path.join(importer.archive, importer.prefix)
  1113.         else:
  1114.             self.module_path = importer.archive
  1115.         self._setup_prefix()
  1116.  
  1117.  
  1118. _distribution_finders = { }
  1119.  
  1120. def register_finder(importer_type, distribution_finder):
  1121.     _distribution_finders[importer_type] = distribution_finder
  1122.  
  1123.  
  1124. def find_distributions(path_item, only = False):
  1125.     importer = get_importer(path_item)
  1126.     finder = _find_adapter(_distribution_finders, importer)
  1127.     return finder(importer, path_item, only)
  1128.  
  1129.  
  1130. def find_in_zip(importer, path_item, only = False):
  1131.     metadata = EggMetadata(importer)
  1132.     if metadata.has_metadata('PKG-INFO'):
  1133.         yield Distribution.from_filename(path_item, metadata = metadata)
  1134.     
  1135.     if only:
  1136.         return None
  1137.     
  1138.     for subitem in metadata.resource_listdir('/'):
  1139.         if subitem.endswith('.egg'):
  1140.             subpath = os.path.join(path_item, subitem)
  1141.             for dist in find_in_zip(zipimport.zipimporter(subpath), subpath):
  1142.                 yield dist
  1143.             
  1144.     
  1145.  
  1146. register_finder(zipimport.zipimporter, find_in_zip)
  1147.  
  1148. def StringIO(*args, **kw):
  1149.     global StringIO
  1150.     
  1151.     try:
  1152.         StringIO = StringIO
  1153.         import cStringIO
  1154.     except ImportError:
  1155.         StringIO = StringIO
  1156.         import StringIO
  1157.  
  1158.     return StringIO(*args, **kw)
  1159.  
  1160.  
  1161. def find_nothing(importer, path_item, only = False):
  1162.     return ()
  1163.  
  1164. register_finder(object, find_nothing)
  1165.  
  1166. def find_on_path(importer, path_item, only = False):
  1167.     path_item = _normalize_cached(path_item)
  1168.     if os.path.isdir(path_item):
  1169.         if path_item.lower().endswith('.egg'):
  1170.             yield Distribution.from_filename(path_item, metadata = PathMetadata(path_item, os.path.join(path_item, 'EGG-INFO')))
  1171.         else:
  1172.             for entry in os.listdir(path_item):
  1173.                 lower = entry.lower()
  1174.                 if lower.endswith('.egg-info'):
  1175.                     fullpath = os.path.join(path_item, entry)
  1176.                     if os.path.isdir(fullpath):
  1177.                         metadata = PathMetadata(path_item, fullpath)
  1178.                     else:
  1179.                         metadata = FileMetadata(fullpath)
  1180.                     yield Distribution.from_location(path_item, entry, metadata, precedence = DEVELOP_DIST)
  1181.                     continue
  1182.                 if not only and lower.endswith('.egg'):
  1183.                     for dist in find_distributions(os.path.join(path_item, entry)):
  1184.                         yield dist
  1185.                     
  1186.                 if not only and lower.endswith('.egg-link'):
  1187.                     for line in file(os.path.join(path_item, entry)):
  1188.                         if not line.strip():
  1189.                             continue
  1190.                         
  1191.                         for item in find_distributions(os.path.join(path_item, line.rstrip())):
  1192.                             yield item
  1193.                         
  1194.                         break
  1195.                     
  1196.             
  1197.     
  1198.  
  1199. register_finder(pkgutil.ImpImporter, find_on_path)
  1200. _namespace_handlers = { }
  1201. _namespace_packages = { }
  1202.  
  1203. def register_namespace_handler(importer_type, namespace_handler):
  1204.     _namespace_handlers[importer_type] = namespace_handler
  1205.  
  1206.  
  1207. def _handle_ns(packageName, path_item):
  1208.     importer = get_importer(path_item)
  1209.     if importer is None:
  1210.         return None
  1211.     
  1212.     loader = importer.find_module(packageName)
  1213.     if loader is None:
  1214.         return None
  1215.     
  1216.     module = sys.modules.get(packageName)
  1217.     if module is None:
  1218.         module = sys.modules[packageName] = new.module(packageName)
  1219.         module.__path__ = []
  1220.         _set_parent_ns(packageName)
  1221.     elif not hasattr(module, '__path__'):
  1222.         raise TypeError('Not a package:', packageName)
  1223.     
  1224.     handler = _find_adapter(_namespace_handlers, importer)
  1225.     subpath = handler(importer, path_item, packageName, module)
  1226.     if subpath is not None:
  1227.         path = module.__path__
  1228.         path.append(subpath)
  1229.         loader.load_module(packageName)
  1230.         module.__path__ = path
  1231.     
  1232.     return subpath
  1233.  
  1234.  
  1235. def declare_namespace(packageName):
  1236.     imp.acquire_lock()
  1237.     
  1238.     try:
  1239.         if packageName in _namespace_packages:
  1240.             return None
  1241.         
  1242.         path = sys.path
  1243.         parent = None
  1244.         if '.' in packageName:
  1245.             parent = '.'.join(packageName.split('.')[:-1])
  1246.             declare_namespace(parent)
  1247.             __import__(parent)
  1248.             
  1249.             try:
  1250.                 path = sys.modules[parent].__path__
  1251.             except AttributeError:
  1252.                 raise TypeError('Not a package:', parent)
  1253.             except:
  1254.                 None<EXCEPTION MATCH>AttributeError
  1255.             
  1256.  
  1257.         None<EXCEPTION MATCH>AttributeError
  1258.         _namespace_packages.setdefault(parent, []).append(packageName)
  1259.         _namespace_packages.setdefault(packageName, [])
  1260.         for path_item in path:
  1261.             _handle_ns(packageName, path_item)
  1262.     finally:
  1263.         imp.release_lock()
  1264.  
  1265.  
  1266.  
  1267. def fixup_namespace_packages(path_item, parent = None):
  1268.     imp.acquire_lock()
  1269.     
  1270.     try:
  1271.         for package in _namespace_packages.get(parent, ()):
  1272.             subpath = _handle_ns(package, path_item)
  1273.             if subpath:
  1274.                 fixup_namespace_packages(subpath, package)
  1275.                 continue
  1276.     finally:
  1277.         imp.release_lock()
  1278.  
  1279.  
  1280.  
  1281. def file_ns_handler(importer, path_item, packageName, module):
  1282.     subpath = os.path.join(path_item, packageName.split('.')[-1])
  1283.     normalized = _normalize_cached(subpath)
  1284.     for item in module.__path__:
  1285.         if _normalize_cached(item) == normalized:
  1286.             break
  1287.             continue
  1288.     else:
  1289.         return subpath
  1290.  
  1291. register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
  1292. register_namespace_handler(zipimport.zipimporter, file_ns_handler)
  1293.  
  1294. def null_ns_handler(importer, path_item, packageName, module):
  1295.     pass
  1296.  
  1297. register_namespace_handler(object, null_ns_handler)
  1298.  
  1299. def normalize_path(filename):
  1300.     return os.path.normcase(os.path.realpath(filename))
  1301.  
  1302.  
  1303. def _normalize_cached(filename, _cache = { }):
  1304.     
  1305.     try:
  1306.         return _cache[filename]
  1307.     except KeyError:
  1308.         _cache[filename] = result = normalize_path(filename)
  1309.         return result
  1310.  
  1311.  
  1312.  
  1313. def _set_parent_ns(packageName):
  1314.     parts = packageName.split('.')
  1315.     name = parts.pop()
  1316.     if parts:
  1317.         parent = '.'.join(parts)
  1318.         setattr(sys.modules[parent], name, sys.modules[packageName])
  1319.     
  1320.  
  1321.  
  1322. def yield_lines(strs):
  1323.     if isinstance(strs, basestring):
  1324.         for s in strs.splitlines():
  1325.             s = s.strip()
  1326.             if s and not s.startswith('#'):
  1327.                 yield s
  1328.                 continue
  1329.         
  1330.     else:
  1331.         for ss in strs:
  1332.             for s in yield_lines(ss):
  1333.                 yield s
  1334.             
  1335.         
  1336.  
  1337. LINE_END = re.compile('\\s*(#.*)?$').match
  1338. CONTINUE = re.compile('\\s*\\\\\\s*(#.*)?$').match
  1339. DISTRO = re.compile('\\s*((\\w|[-.])+)').match
  1340. VERSION = re.compile('\\s*(<=?|>=?|==|!=)\\s*((\\w|[-.])+)').match
  1341. COMMA = re.compile('\\s*,').match
  1342. OBRACKET = re.compile('\\s*\\[').match
  1343. CBRACKET = re.compile('\\s*\\]').match
  1344. MODULE = re.compile('\\w+(\\.\\w+)*$').match
  1345. EGG_NAME = re.compile('(?P<name>[^-]+)( -(?P<ver>[^-]+) (-py(?P<pyver>[^-]+) (-(?P<plat>.+))? )? )?', re.VERBOSE | re.IGNORECASE).match
  1346. component_re = re.compile('(\\d+ | [a-z]+ | \\.| -)', re.VERBOSE)
  1347. replace = {
  1348.     'pre': 'c',
  1349.     'preview': 'c',
  1350.     '-': 'final-',
  1351.     'rc': 'c',
  1352.     'dev': '@' }.get
  1353.  
  1354. def _parse_version_parts(s):
  1355.     for part in component_re.split(s):
  1356.         part = replace(part, part)
  1357.         if not part or part == '.':
  1358.             continue
  1359.         
  1360.         if part[:1] in '0123456789':
  1361.             yield part.zfill(8)
  1362.             continue
  1363.         yield '*' + part
  1364.     
  1365.     yield '*final'
  1366.  
  1367.  
  1368. def parse_version(s):
  1369.     parts = []
  1370.     for part in _parse_version_parts(s.lower()):
  1371.         if part.startswith('*'):
  1372.             if part < '*final':
  1373.                 while parts and parts[-1] == '*final-':
  1374.                     parts.pop()
  1375.             
  1376.             while parts and parts[-1] == '00000000':
  1377.                 parts.pop()
  1378.         
  1379.         parts.append(part)
  1380.     
  1381.     return tuple(parts)
  1382.  
  1383.  
  1384. class EntryPoint(object):
  1385.     
  1386.     def __init__(self, name, module_name, attrs = (), extras = (), dist = None):
  1387.         if not MODULE(module_name):
  1388.             raise ValueError('Invalid module name', module_name)
  1389.         
  1390.         self.name = name
  1391.         self.module_name = module_name
  1392.         self.attrs = tuple(attrs)
  1393.         self.extras = Requirement.parse('x[%s]' % ','.join(extras)).extras
  1394.         self.dist = dist
  1395.  
  1396.     
  1397.     def __str__(self):
  1398.         s = '%s = %s' % (self.name, self.module_name)
  1399.         if self.attrs:
  1400.             s += ':' + '.'.join(self.attrs)
  1401.         
  1402.         if self.extras:
  1403.             s += ' [%s]' % ','.join(self.extras)
  1404.         
  1405.         return s
  1406.  
  1407.     
  1408.     def __repr__(self):
  1409.         return 'EntryPoint.parse(%r)' % str(self)
  1410.  
  1411.     
  1412.     def load(self, require = True, env = None, installer = None):
  1413.         if require:
  1414.             self.require(env, installer)
  1415.         
  1416.         entry = __import__(self.module_name, globals(), globals(), [
  1417.             '__name__'])
  1418.         for attr in self.attrs:
  1419.             
  1420.             try:
  1421.                 entry = getattr(entry, attr)
  1422.             continue
  1423.             except AttributeError:
  1424.                 raise ImportError('%r has no %r attribute' % (entry, attr))
  1425.                 continue
  1426.             
  1427.  
  1428.         
  1429.         return entry
  1430.  
  1431.     
  1432.     def require(self, env = None, installer = None):
  1433.         if self.extras and not (self.dist):
  1434.             raise UnknownExtra("Can't require() without a distribution", self)
  1435.         
  1436.         map(working_set.add, working_set.resolve(self.dist.requires(self.extras), env, installer))
  1437.  
  1438.     
  1439.     def parse(cls, src, dist = None):
  1440.         
  1441.         try:
  1442.             attrs = extras = ()
  1443.             (name, value) = src.split('=', 1)
  1444.             if '[' in value:
  1445.                 (value, extras) = value.split('[', 1)
  1446.                 req = Requirement.parse('x[' + extras)
  1447.                 if req.specs:
  1448.                     raise ValueError
  1449.                 
  1450.                 extras = req.extras
  1451.             
  1452.             if ':' in value:
  1453.                 (value, attrs) = value.split(':', 1)
  1454.                 if not MODULE(attrs.rstrip()):
  1455.                     raise ValueError
  1456.                 
  1457.                 attrs = attrs.rstrip().split('.')
  1458.         except ValueError:
  1459.             raise ValueError("EntryPoint must be in 'name=module:attrs [extras]' format", src)
  1460.  
  1461.         return cls(name.strip(), value.strip(), attrs, extras, dist)
  1462.  
  1463.     parse = classmethod(parse)
  1464.     
  1465.     def parse_group(cls, group, lines, dist = None):
  1466.         if not MODULE(group):
  1467.             raise ValueError('Invalid group name', group)
  1468.         
  1469.         this = { }
  1470.         for line in yield_lines(lines):
  1471.             ep = cls.parse(line, dist)
  1472.             if ep.name in this:
  1473.                 raise ValueError('Duplicate entry point', group, ep.name)
  1474.             
  1475.             this[ep.name] = ep
  1476.         
  1477.         return this
  1478.  
  1479.     parse_group = classmethod(parse_group)
  1480.     
  1481.     def parse_map(cls, data, dist = None):
  1482.         if isinstance(data, dict):
  1483.             data = data.items()
  1484.         else:
  1485.             data = split_sections(data)
  1486.         maps = { }
  1487.         for group, lines in data:
  1488.             if group is None:
  1489.                 if not lines:
  1490.                     continue
  1491.                 
  1492.                 raise ValueError('Entry points must be listed in groups')
  1493.             
  1494.             group = group.strip()
  1495.             if group in maps:
  1496.                 raise ValueError('Duplicate group name', group)
  1497.             
  1498.             maps[group] = cls.parse_group(group, lines, dist)
  1499.         
  1500.         return maps
  1501.  
  1502.     parse_map = classmethod(parse_map)
  1503.  
  1504.  
  1505. class Distribution(object):
  1506.     
  1507.     def __init__(self, location = None, metadata = None, project_name = None, version = None, py_version = PY_MAJOR, platform = None, precedence = EGG_DIST):
  1508.         if not project_name:
  1509.             pass
  1510.         self.project_name = safe_name('Unknown')
  1511.         if version is not None:
  1512.             self._version = safe_version(version)
  1513.         
  1514.         self.py_version = py_version
  1515.         self.platform = platform
  1516.         self.location = location
  1517.         self.precedence = precedence
  1518.         if not metadata:
  1519.             pass
  1520.         self._provider = empty_provider
  1521.  
  1522.     
  1523.     def from_location(cls, location, basename, metadata = None, **kw):
  1524.         (project_name, version, py_version, platform) = [
  1525.             None] * 4
  1526.         (basename, ext) = os.path.splitext(basename)
  1527.         if ext.lower() in ('.egg', '.egg-info'):
  1528.             match = EGG_NAME(basename)
  1529.             if match:
  1530.                 (project_name, version, py_version, platform) = match.group('name', 'ver', 'pyver', 'plat')
  1531.             
  1532.         
  1533.         return cls(location, metadata, project_name = project_name, version = version, py_version = py_version, platform = platform, **kw)
  1534.  
  1535.     from_location = classmethod(from_location)
  1536.     hashcmp = property((lambda self: if not self.location:
  1537. pass(getattr(self, 'parsed_version', ()), self.precedence, self.key, -len(''), self.location, self.py_version, self.platform)))
  1538.     
  1539.     def __cmp__(self, other):
  1540.         return cmp(self.hashcmp, other)
  1541.  
  1542.     
  1543.     def __hash__(self):
  1544.         return hash(self.hashcmp)
  1545.  
  1546.     
  1547.     def key(self):
  1548.         
  1549.         try:
  1550.             return self._key
  1551.         except AttributeError:
  1552.             self._key = key = self.project_name.lower()
  1553.             return key
  1554.  
  1555.  
  1556.     key = property(key)
  1557.     
  1558.     def parsed_version(self):
  1559.         
  1560.         try:
  1561.             return self._parsed_version
  1562.         except AttributeError:
  1563.             self._parsed_version = pv = parse_version(self.version)
  1564.             return pv
  1565.  
  1566.  
  1567.     parsed_version = property(parsed_version)
  1568.     
  1569.     def version(self):
  1570.         
  1571.         try:
  1572.             return self._version
  1573.         except AttributeError:
  1574.             for line in self._get_metadata('PKG-INFO'):
  1575.                 if line.lower().startswith('version:'):
  1576.                     self._version = safe_version(line.split(':', 1)[1].strip())
  1577.                     return self._version
  1578.                     continue
  1579.             else:
  1580.                 raise ValueError("Missing 'Version:' header and/or PKG-INFO file", self)
  1581.  
  1582.  
  1583.     version = property(version)
  1584.     
  1585.     def _dep_map(self):
  1586.         
  1587.         try:
  1588.             return self._Distribution__dep_map
  1589.         except AttributeError:
  1590.             dm = self._Distribution__dep_map = {
  1591.                 None: [] }
  1592.             for name in ('requires.txt', 'depends.txt'):
  1593.                 for extra, reqs in split_sections(self._get_metadata(name)):
  1594.                     if extra:
  1595.                         extra = safe_extra(extra)
  1596.                     
  1597.                     dm.setdefault(extra, []).extend(parse_requirements(reqs))
  1598.                 
  1599.             
  1600.             return dm
  1601.  
  1602.  
  1603.     _dep_map = property(_dep_map)
  1604.     
  1605.     def requires(self, extras = ()):
  1606.         dm = self._dep_map
  1607.         deps = []
  1608.         deps.extend(dm.get(None, ()))
  1609.         for ext in extras:
  1610.             
  1611.             try:
  1612.                 deps.extend(dm[safe_extra(ext)])
  1613.             continue
  1614.             except KeyError:
  1615.                 raise UnknownExtra('%s has no such extra feature %r' % (self, ext))
  1616.                 continue
  1617.             
  1618.  
  1619.         
  1620.         return deps
  1621.  
  1622.     
  1623.     def _get_metadata(self, name):
  1624.         if self.has_metadata(name):
  1625.             for line in self.get_metadata_lines(name):
  1626.                 yield line
  1627.             
  1628.         
  1629.  
  1630.     
  1631.     def activate(self, path = None):
  1632.         if path is None:
  1633.             path = sys.path
  1634.         
  1635.         self.insert_on(path)
  1636.         if path is sys.path:
  1637.             fixup_namespace_packages(self.location)
  1638.             for pkg in self._get_metadata('namespace_packages.txt'):
  1639.                 if pkg in sys.modules:
  1640.                     declare_namespace(pkg)
  1641.                     continue
  1642.             
  1643.         
  1644.  
  1645.     
  1646.     def egg_name(self):
  1647.         if not self.py_version:
  1648.             pass
  1649.         filename = '%s-%s-py%s' % (to_filename(self.project_name), to_filename(self.version), PY_MAJOR)
  1650.         if self.platform:
  1651.             filename += '-' + self.platform
  1652.         
  1653.         return filename
  1654.  
  1655.     
  1656.     def __repr__(self):
  1657.         if self.location:
  1658.             return '%s (%s)' % (self, self.location)
  1659.         else:
  1660.             return str(self)
  1661.  
  1662.     
  1663.     def __str__(self):
  1664.         
  1665.         try:
  1666.             version = getattr(self, 'version', None)
  1667.         except ValueError:
  1668.             version = None
  1669.  
  1670.         if not version:
  1671.             pass
  1672.         version = '[unknown version]'
  1673.         return '%s %s' % (self.project_name, version)
  1674.  
  1675.     
  1676.     def __getattr__(self, attr):
  1677.         if attr.startswith('_'):
  1678.             raise AttributeError, attr
  1679.         
  1680.         return getattr(self._provider, attr)
  1681.  
  1682.     
  1683.     def from_filename(cls, filename, metadata = None, **kw):
  1684.         return cls.from_location(_normalize_cached(filename), os.path.basename(filename), metadata, **kw)
  1685.  
  1686.     from_filename = classmethod(from_filename)
  1687.     
  1688.     def as_requirement(self):
  1689.         return Requirement.parse('%s==%s' % (self.project_name, self.version))
  1690.  
  1691.     
  1692.     def load_entry_point(self, group, name):
  1693.         ep = self.get_entry_info(group, name)
  1694.         if ep is None:
  1695.             raise ImportError('Entry point %r not found' % ((group, name),))
  1696.         
  1697.         return ep.load()
  1698.  
  1699.     
  1700.     def get_entry_map(self, group = None):
  1701.         
  1702.         try:
  1703.             ep_map = self._ep_map
  1704.         except AttributeError:
  1705.             ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self)
  1706.  
  1707.         if group is not None:
  1708.             return ep_map.get(group, { })
  1709.         
  1710.         return ep_map
  1711.  
  1712.     
  1713.     def get_entry_info(self, group, name):
  1714.         return self.get_entry_map(group).get(name)
  1715.  
  1716.     
  1717.     def insert_on(self, path, loc = None):
  1718.         if not loc:
  1719.             pass
  1720.         loc = self.location
  1721.         if not loc:
  1722.             return None
  1723.         
  1724.         if path is sys.path:
  1725.             self.check_version_conflict()
  1726.         
  1727.         nloc = _normalize_cached(loc)
  1728.         bdir = os.path.dirname(nloc)
  1729.         npath = map(_normalize_cached, path)
  1730.         bp = None
  1731.         for p, item in enumerate(npath):
  1732.             if item == nloc:
  1733.                 break
  1734.                 continue
  1735.             if item == bdir and self.precedence == EGG_DIST:
  1736.                 path.insert(p, loc)
  1737.                 npath.insert(p, nloc)
  1738.                 break
  1739.                 continue
  1740.         else:
  1741.             return None
  1742.         while None:
  1743.             
  1744.             try:
  1745.                 np = npath.index(nloc, p + 1)
  1746.             except ValueError:
  1747.                 break
  1748.                 continue
  1749.  
  1750.             del npath[np]
  1751.             del path[np]
  1752.             p = np
  1753.             continue
  1754.             return None
  1755.  
  1756.     
  1757.     def check_version_conflict(self):
  1758.         if self.key == 'setuptools':
  1759.             return None
  1760.         
  1761.         nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
  1762.         loc = normalize_path(self.location)
  1763.         for modname in self._get_metadata('top_level.txt'):
  1764.             if modname not in sys.modules and modname in nsp or modname in _namespace_packages:
  1765.                 continue
  1766.             
  1767.             fn = getattr(sys.modules[modname], '__file__', None)
  1768.             if fn and normalize_path(fn).startswith(loc):
  1769.                 continue
  1770.             
  1771.             issue_warning('Module %s was already imported from %s, but %s is being added to sys.path' % (modname, fn, self.location))
  1772.         
  1773.  
  1774.     
  1775.     def has_version(self):
  1776.         
  1777.         try:
  1778.             self.version
  1779.         except ValueError:
  1780.             issue_warning('Unbuilt egg for ' + repr(self))
  1781.             return False
  1782.  
  1783.         return True
  1784.  
  1785.     
  1786.     def clone(self, **kw):
  1787.         for attr in ('project_name', 'version', 'py_version', 'platform', 'location', 'precedence'):
  1788.             kw.setdefault(attr, getattr(self, attr, None))
  1789.         
  1790.         kw.setdefault('metadata', self._provider)
  1791.         return self.__class__(**kw)
  1792.  
  1793.     
  1794.     def extras(self):
  1795.         return _[1]
  1796.  
  1797.     extras = property(extras)
  1798.  
  1799.  
  1800. def issue_warning(*args, **kw):
  1801.     level = 1
  1802.     g = globals()
  1803.     
  1804.     try:
  1805.         while sys._getframe(level).f_globals is g:
  1806.             level += 1
  1807.     except ValueError:
  1808.         pass
  1809.  
  1810.     warn = warn
  1811.     import warnings
  1812.     warn(stacklevel = level + 1, *args, **kw)
  1813.  
  1814.  
  1815. def parse_requirements(strs):
  1816.     lines = iter(yield_lines(strs))
  1817.     
  1818.     def scan_list(ITEM, TERMINATOR, line, p, groups, item_name):
  1819.         items = []
  1820.         while not TERMINATOR(line, p):
  1821.             if CONTINUE(line, p):
  1822.                 
  1823.                 try:
  1824.                     line = lines.next()
  1825.                     p = 0
  1826.                 except StopIteration:
  1827.                     raise ValueError('\\ must not appear on the last nonblank line')
  1828.                 except:
  1829.                     None<EXCEPTION MATCH>StopIteration
  1830.                 
  1831.  
  1832.             None<EXCEPTION MATCH>StopIteration
  1833.             match = ITEM(line, p)
  1834.             if not match:
  1835.                 raise ValueError('Expected ' + item_name + ' in', line, 'at', line[p:])
  1836.             
  1837.             items.append(match.group(*groups))
  1838.             p = match.end()
  1839.             match = COMMA(line, p)
  1840.             if match:
  1841.                 p = match.end()
  1842.                 continue
  1843.             if not TERMINATOR(line, p):
  1844.                 raise ValueError("Expected ',' or end-of-list in", line, 'at', line[p:])
  1845.                 continue
  1846.         match = TERMINATOR(line, p)
  1847.         if match:
  1848.             p = match.end()
  1849.         
  1850.         return (line, p, items)
  1851.  
  1852.     for line in lines:
  1853.         match = DISTRO(line)
  1854.         if not match:
  1855.             raise ValueError('Missing distribution spec', line)
  1856.         
  1857.         project_name = match.group(1)
  1858.         p = match.end()
  1859.         extras = []
  1860.         match = OBRACKET(line, p)
  1861.         if match:
  1862.             p = match.end()
  1863.             (line, p, extras) = scan_list(DISTRO, CBRACKET, line, p, (1,), "'extra' name")
  1864.         
  1865.         (line, p, specs) = scan_list(VERSION, LINE_END, line, p, (1, 2), 'version spec')
  1866.         specs = [ (op, safe_version(val)) for op, val in specs ]
  1867.         yield Requirement(project_name, specs, extras)
  1868.         []
  1869.     
  1870.  
  1871.  
  1872. def _sort_dists(dists):
  1873.     tmp = [ (dist.hashcmp, dist) for dist in dists ]
  1874.     tmp.sort()
  1875.     dists[::-1] = [ d for hc, d in tmp ]
  1876.  
  1877.  
  1878. class Requirement:
  1879.     
  1880.     def __init__(self, project_name, specs, extras):
  1881.         self.unsafe_name = project_name
  1882.         project_name = safe_name(project_name)
  1883.         self.project_name = project_name
  1884.         self.key = project_name.lower()
  1885.         index = [ (parse_version(v), state_machine[op], op, v) for op, v in specs ]
  1886.         index.sort()
  1887.         self.specs = [ (op, ver) for parsed, trans, op, ver in index ]
  1888.         self.index = index
  1889.         self.extras = tuple(map(safe_extra, extras))
  1890.         self.hashCmp = ([], []([ (op, parsed) for parsed, trans, op, ver in index ]), frozenset(self.extras))
  1891.         self._Requirement__hash = hash(self.hashCmp)
  1892.  
  1893.     
  1894.     def __str__(self):
  1895.         specs = []([ ''.join(s) for s in self.specs ])
  1896.         extras = ','.join(self.extras)
  1897.         return '%s%s%s' % (self.project_name, extras, specs)
  1898.  
  1899.     
  1900.     def __eq__(self, other):
  1901.         if isinstance(other, Requirement):
  1902.             pass
  1903.         return self.hashCmp == other.hashCmp
  1904.  
  1905.     
  1906.     def __contains__(self, item):
  1907.         if isinstance(item, Distribution):
  1908.             if item.key != self.key:
  1909.                 return False
  1910.             
  1911.             if self.index:
  1912.                 item = item.parsed_version
  1913.             
  1914.         elif isinstance(item, basestring):
  1915.             item = parse_version(item)
  1916.         
  1917.         last = None
  1918.         for parsed, trans, op, ver in self.index:
  1919.             action = trans[cmp(item, parsed)]
  1920.             if action == 'F':
  1921.                 return False
  1922.                 continue
  1923.             if action == 'T':
  1924.                 return True
  1925.                 continue
  1926.             if action == '+':
  1927.                 last = True
  1928.                 continue
  1929.             if action == '-' or last is None:
  1930.                 last = False
  1931.                 continue
  1932.         
  1933.         if last is None:
  1934.             last = True
  1935.         
  1936.         return last
  1937.  
  1938.     
  1939.     def __hash__(self):
  1940.         return self._Requirement__hash
  1941.  
  1942.     
  1943.     def __repr__(self):
  1944.         return 'Requirement.parse(%r)' % str(self)
  1945.  
  1946.     
  1947.     def parse(s):
  1948.         reqs = list(parse_requirements(s))
  1949.         if reqs:
  1950.             if len(reqs) == 1:
  1951.                 return reqs[0]
  1952.             
  1953.             raise ValueError('Expected only one requirement', s)
  1954.         
  1955.         raise ValueError('No requirements found', s)
  1956.  
  1957.     parse = staticmethod(parse)
  1958.  
  1959. state_machine = {
  1960.     '<': '--T',
  1961.     '<=': 'T-T',
  1962.     '>': 'F+F',
  1963.     '>=': 'T+F',
  1964.     '==': 'T..',
  1965.     '!=': 'F++' }
  1966.  
  1967. def _get_mro(cls):
  1968.     if not isinstance(cls, type):
  1969.         
  1970.         class cls(cls, object):
  1971.             pass
  1972.  
  1973.         return cls.__mro__[1:]
  1974.     
  1975.     return cls.__mro__
  1976.  
  1977.  
  1978. def _find_adapter(registry, ob):
  1979.     for t in _get_mro(getattr(ob, '__class__', type(ob))):
  1980.         if t in registry:
  1981.             return registry[t]
  1982.             continue
  1983.     
  1984.  
  1985.  
  1986. def ensure_directory(path):
  1987.     dirname = os.path.dirname(path)
  1988.     if not os.path.isdir(dirname):
  1989.         os.makedirs(dirname)
  1990.     
  1991.  
  1992.  
  1993. def split_sections(s):
  1994.     section = None
  1995.     content = []
  1996.     for line in yield_lines(s):
  1997.         if line.startswith('['):
  1998.             if line.endswith(']'):
  1999.                 if section or content:
  2000.                     yield (section, content)
  2001.                 
  2002.                 section = line[1:-1].strip()
  2003.                 content = []
  2004.             else:
  2005.                 raise ValueError('Invalid section heading', line)
  2006.         line.endswith(']')
  2007.         content.append(line)
  2008.     
  2009.     yield (section, content)
  2010.  
  2011.  
  2012. def _mkstemp(*args, **kw):
  2013.     mkstemp = mkstemp
  2014.     import tempfile
  2015.     old_open = os.open
  2016.     
  2017.     try:
  2018.         os.open = os_open
  2019.         return mkstemp(*args, **kw)
  2020.     finally:
  2021.         os.open = old_open
  2022.  
  2023.  
  2024. _manager = ResourceManager()
  2025.  
  2026. def _initialize(g):
  2027.     for name in dir(_manager):
  2028.         if not name.startswith('_'):
  2029.             g[name] = getattr(_manager, name)
  2030.             continue
  2031.     
  2032.  
  2033. _initialize(globals())
  2034. working_set = WorkingSet()
  2035.  
  2036. try:
  2037.     from __main__ import __requires__
  2038. except ImportError:
  2039.     pass
  2040.  
  2041.  
  2042. try:
  2043.     working_set.require(__requires__)
  2044. except VersionConflict:
  2045.     working_set = WorkingSet([])
  2046.     for dist in working_set.resolve(parse_requirements(__requires__), Environment()):
  2047.         working_set.add(dist)
  2048.     
  2049.     for entry in sys.path:
  2050.         if entry not in working_set.entries:
  2051.             working_set.add_entry(entry)
  2052.         
  2053.     
  2054.     sys.path[:] = working_set.entries
  2055.  
  2056. require = working_set.require
  2057. iter_entry_points = working_set.iter_entry_points
  2058. add_activation_listener = working_set.subscribe
  2059. run_script = working_set.run_script
  2060. run_main = run_script
  2061. add_activation_listener((lambda dist: dist.activate()))
  2062. working_set.entries = []
  2063. map(working_set.add_entry, sys.path)
  2064.